<?php

namespace Parser\Separator;

use Parser\Enquiry;
use Parser\Parser;
use Parser\Repetition;

class ALL_TRUST implements BaseSeparator
{
    public static $ApiKindList = [
        3000 => '030006', //车损
        4000 => '030018', //三者
        5002 => '030101', //司机
        5001 => '030102', //乘客
    ];

    private $errorTip;

    public function interpreter(array $array, $parser)
    {
        if ($this->error($array, $parser)) {
            return;
        }

        $parser->result = $this->analysis($array);
    }

    /**
     *错误解析
     * Author:ls
     *
     * @param $array
     * @param Parser $parser
     * @return bool
     */
    public function error(&$array, $parser): bool
    {
        if ($array['RESULT_TYPE'] != 'SUCCESS') {
            $parser->message = $array['RESULT_MSG'] ?? "";
            $parser->code = '500';
            return true;
        }
        if (!$data = $array['WEB_DATA'] ?? '') {
            $parser->message = $array['RESULT_MSG'] ?? "";
            $parser->code = '500';
            return true;
        }

        //重复投保
        if ($message = $array['RESULT_MSG'] ?? '') {
            if (preg_match('/重复投保/', $message)) {
                $this->errorTip = '商业险重复投保';
            }
        }


        $array = array_combine(array_column($array['WEB_DATA'], 'dwName'), $array['WEB_DATA']);

        if (!key_exists('prodDef.vhl.Cvrg_DW', $array)) {
            $parser->message = '未找到险种';
            $parser->code = '500';
            return true;
        }

        return false;
    }


    public function analysis($array): array
    {

        $enquiry = new Enquiry();
        //交强险
        if (key_exists('prodDef.vhl.VsTax_DW', $array)) {
            $enquiry->setTaxTotal((string)($array['prodDef.vhl.VsTax_DW']['dataObjVoList'][0]['attributeVoList']['VsTax.NAnnUnitTaxAmt']['value'] ?? '0'));
            $enquiry->setTaxPremium((string)($array['prodDef.vhl.VsTax_DW']['dataObjVoList'][0]['attributeVoList']['VsTax.CTaxUnit']['value'] ?? '0'));
        }

        //折扣
        if (key_exists('prodDef.vhl.Base_DW', $array)) {
            $enquiry->setVCIDiscount((string)($array['prodDef.vhl.Base_DW']['dataObjVoList'][0]['attributeVoList']['SY_Base.NIrrRatio']['value'] ?? '0'));
        }
        //自主定价系数
        if (key_exists('prodDef.vhl.PrmCoef_DW', $array)) {
            $enquiry->setIndependentPriceRatio((string)$array['prodDef.vhl.PrmCoef_DW']['dataObjVoList'][0]['attributeVoList']['SY_PrmCoef.NPricingAdjustValue']['text'] ?? '');
        }
        //无赔款优待系数NCD
        if (key_exists('prodDef.vhl.PrmCoef_DW', $array)) {
            $enquiry->setNCDRate((string)$array['prodDef.vhl.PrmCoef_DW']['dataObjVoList'][0]['attributeVoList']['SY_PrmCoef.NAgoClmRecQuick']['value'] ?? '0');
        }
        $array = $array['prodDef.vhl.Cvrg_DW'];

        foreach ($array['dataObjVoList'] as $value) {

            //交强险
            if (($value['attributeVoList']['Cvrg.CCvrgNo']['value'] ?? '') == '030050') {
                $enquiry->setTCITotal($value['attributeVoList']['Cvrg.NPrm']['value'] ?? '0');
                $enquiry->setTCIPremium($value['attributeVoList']['Cvrg.NBasePrm']['value'] ?? '0');
            } else {
                $enquiry->VCITotalAppend($value['attributeVoList']['Cvrg.NPrm']['value'] ?? '0');
                $enquiry->VCIPremiumAppend($value['attributeVoList']['Cvrg.NBefPrm']['value'] ?? '0');

                $coverages['code'] = (string)array_search($value['attributeVoList']['Cvrg.CCvrgNo']['value'], self::$ApiKindList);
                $coverages['shortName'] = (string)$value['attributeVoList']['Cvrg.CCustCvrgNme']['value'] ?? '';
                $coverages['insuredDesc'] = (string)$value['attributeVoList']['Cvrg.NAmtVar']['value'] ?? '';
                $coverages['total'] = (string)$value['attributeVoList']['Cvrg.NPrm']['value'] ?? '';

                $enquiry->setVCICoverages($coverages);
            }
        }

        $enquiry->setTotal();

        if ($this->errorTip) {
            $enquiry->failure();
            $enquiry->setErrorTip('商业险重复投保');
        }

        $enquiry->success();

        return $enquiry->get();
    }

    //数据解析
    public function repetition($array): Repetition
    {
        $repetition = new Repetition();

        if ($repeatMsg = $array['RESULT_MSG'] ?? false) {
            if (mb_strlen($repeatMsg) < 400) {
                return $repetition;
            }
            //数据验证
            preg_match('/车险平台返回信息([\s\S]*)以上为/', $repeatMsg, $matches);
            if (!$matches) {
                return $repetition;
            }
            $repeatMsg = explode("\n", trim($matches[1]));
            if (count($repeatMsg) < 10) {
                return $repetition;
            }

            $coverage = [];

            foreach ($repeatMsg as &$value) {
                if (!$value) {
                    break;
                }
                $value = explode('：', $value);

                $column = trim($value[0]);
                $v = trim($value[2] ?? '');

                $value = trim($value[1]);

                switch ($column) {
                    case '重复投保保单号':
                        $repetition->setLastPolicy($value);
                        break;
                    case '保险公司代码':
                    case '保险公司名称':
                        $repetition->setLastCompany($value);
                        break;
                    case '起保日期':
                        $repetition->setLastStartAt(date('Y-m-d H:i:s', strtotime($value)));
                        break;
                    case '终保日期':
                        $repetition->setLastEndTime(date('Y-m-d H:i:s', strtotime($value)));
                        break;
                    case '签单日期':
                        $repetition->setLastSignTime(date('Y-m-d H:i:s', strtotime($value)));
                        break;
                    case "号牌号码":
                        $repetition->setLicense($value);
                        break;
                    case "险种代码":
                        $coverage[] = $v;

                }
            }
            $repetition->setLastCoverage($coverage);

            if ($repetition->getLastCompany()) {
                $repetition->setStatus('success');
            }
        }
        return $repetition;
    }
}

